package com.delicious.security.config;


import cn.hutool.core.bean.BeanUtil;
import com.delicious.security.entity.SecurityUser;
import com.delicious.system.entity.Role;
import com.delicious.system.entity.User;
import com.delicious.system.mapper.RoleMapper;
import com.delicious.system.mapper.UserMapper;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;
    private final RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userMapper.loadUserByUsername(userName);
        SecurityUser securityUser = new SecurityUser();
        BeanUtil.copyProperties(user, securityUser);
        if (null != user) {
            List<Role> roles = roleMapper.getRolesByUserId(user.getId());
            securityUser.setAuthorities(roles);
        }
        return securityUser;
    }
}
